package com.situ.personal.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.personal.entity.User;


// @WebFilter(filterName = "login", urlPatterns = {"/*"})
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		// Ctrl+Shift+O
		// 哪个用户调用这段代码就是这个用户得到自己的Session
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		//  /user?method=login
		String method = httpServletRequest.getParameter("method");
		
		// 不需要验证登录，直接放行
		if ("/login.jsp".equals(servletPath)
			|| ("/user".equals(servletPath) && "login".equals(method))
			|| "/fail.jsp".equals(servletPath)
			|| "/checkImg".equals(servletPath)) {
			chain.doFilter(request, response);
			return;
		} 
		
		// 需要验证是否登录
		HttpSession session = httpServletRequest.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {// 代表这个用户没有登录
			// 转发操作：用在查找之后转发到jsp页面展示。其余的都可以用重定向
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
			return;
		}
		chain.doFilter(request, response);
		
		
		// 我本來要去登录界面去完成登录，但是LoginFilter里面要判断我有没有登录，
		// 如果没有登录，就重定向到登录界面
		// 所以报错：将您重定向的次数过多。
		// 解决方法：都对完成登录的操作就不去验证
	}

	@Override
	public void destroy() {
		
	}

}
